//
//  AppConfig.m
//  Delicious
//
//  Created by apple on 11-11-4.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AppConfig.h"

//===========================================================================================================

@implementation CCommand

@synthesize m_nCmd;
@synthesize m_mSubCmd;
@synthesize m_CmdInfo;

+(CCommand*)GetCommandWithInfo:(int)cmd SubCmd:(int)subcmd CmdInfo:(id)cmdinfo
{
    CCommand *command = [[[CCommand alloc] init] autorelease];
    
    command.m_nCmd    = cmd;
    command.m_mSubCmd = subcmd;
    command.m_CmdInfo = cmdinfo;
    
    return command;
}

-(void)dealloc
{
    self.m_CmdInfo = nil;
    
    [super dealloc];
}

@end

//===========================================================================================================

@implementation CExAppInfo

@synthesize m_strType;
@synthesize m_strTokenKey;
@synthesize m_strSecret;

-(id)InitWithValue:(NSString*)tokenkey Secret:(NSString*)secret Type:(NSString*)type
{
    self = [super init];
    if (self)
    {
        self.m_strTokenKey = tokenkey;
        self.m_strSecret   = secret;
        self.m_strType     = type;
    }
    
    return self;
}

-(void)dealloc
{
    [m_strSecret release];
    [m_strTokenKey release];
    [m_strType release];
    
    [super dealloc];
}

@end

//===========================================================================================================

@implementation AppConfig

@synthesize m_DeliciousCtrl;
@synthesize m_DelImagesPath;
@synthesize m_FriendsimagesPath;
@synthesize m_DraftPath;
@synthesize m_IConsPath;
@synthesize m_ExAppDic;

@synthesize m_Language;

//@synthesize hostReach;
//@synthesize internetReach;
//@synthesize wifiReach;

@synthesize m_strUDID;

//network
@synthesize m_bIsNetWork;
@synthesize m_bIsCheckNet;
@synthesize m_NetTimer;

static AppConfig  *g_Instance;          //全局

+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (nil == g_Instance)
        {
            g_Instance = [super allocWithZone:zone];
        }
    }
    
    return g_Instance;
}

+(AppConfig*)DefaultAppConfig
{
    if (nil == g_Instance)
    {
        g_Instance = [[AppConfig alloc] init];
    }
    
    return g_Instance;
}

+(void)DestroyAppConfig
{
    [g_Instance release];
    g_Instance = nil;
}

- (id)init
{
    self = [super init];
    if (self) 
    {
        // Initialization code here.
        m_DelImagesPath = [[NSString alloc] initWithFormat:@"%@/Documents/DeliciousImages", NSHomeDirectory()];
        
        m_FriendsimagesPath = [[NSString alloc] initWithFormat:@"%@/Documents/FriendsImages", NSHomeDirectory()];
        
        m_DraftPath = [[NSString alloc] initWithFormat:@"%@/Documents/Draft", NSHomeDirectory()];
        
        m_IConsPath = [[NSString alloc] initWithFormat:@"%@/Documents/icons", NSHomeDirectory()];
        
        //hostReach = nil;
        //internetReach = nil;
        //wifiReach = nil;
        m_bIsCheckNet = NO;
        
        self.m_strUDID = [NSString stringWithFormat:@"%@_iPhone", [UIDevice currentDevice].uniqueIdentifier];
    }
    
    return self;
}

-(void)dealloc
{
    [m_FriendsimagesPath release];
    [m_DelImagesPath release];
    [m_DraftPath release];
    
    //[hostReach release];
    //[internetReach release];
    //[wifiReach release];
    
    [m_strUDID release];
    
    [super dealloc];
}

- (void) configureTextField: (UITextField*) textField imageView: (UIImageView*) imageView reachability: (ReachabilityEx*) curReach
{
    /*NetworkStatus netStatus = [curReach currentReachabilityStatus];
    BOOL connectionRequired= [curReach connectionRequired];
    NSString* statusString= @"";
    switch (netStatus)
    {
        case NotReachable:
        {
            m_bIsNetWork = NO;
            connectionRequired= NO;  
            NSLog(@"no network");
            break;
        }
            
        case ReachableViaWWAN:
        {
            m_bIsNetWork = YES;
            break;
        }
        case ReachableViaWiFi:
        {
            m_bIsNetWork = YES;
            break;
        }
        case ReachableInternet:
        {
            m_bIsNetWork = YES;
            break;
        }
    }
    
    if(connectionRequired)
    {
        statusString = [NSString stringWithFormat: @"%@, Connection Required", statusString];
    }*/
}

- (void) updateInterfaceWithReachability: (ReachabilityEx*) curReach
{
    /*if(curReach == hostReach)
	{
        NetworkStatus netStatus = [curReach currentReachabilityStatus];
        BOOL connectionRequired= [curReach connectionRequired];
        BOOL b = (netStatus != ReachableViaWWAN);
        b= NO;
        NSString* baseLabel=  @"";
        if(connectionRequired)
        {
            baseLabel=  @"Cellular data network is available.\n  Internet traffic will be routed through it after a connection is established.";
        }
        else
        {
            baseLabel=  @"Cellular data network is active.\n  Internet traffic will be routed through it.";
        }
    }
	if(curReach == internetReach)
	{	
		[self configureTextField:nil imageView:nil reachability:curReach];
	}
	if(curReach == wifiReach)
	{	
		[self configureTextField:nil imageView:nil reachability:curReach];
	}
     */
}

//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
	ReachabilityEx* curReach = [note object];
	NSParameterAssert([curReach isKindOfClass: [ReachabilityEx class]]);
	[self updateInterfaceWithReachability: curReach];
}

-(BOOL)CheckNetwork
{
    /*if (!hostReach)
    {
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
        
        //Change the host name here to change the server your monitoring
        hostReach = [[ReachabilityEx reachabilityWithHostName: @"www.apple.com"] retain];
        [hostReach startNotifier];
        [self updateInterfaceWithReachability: hostReach];
        
        internetReach = [[ReachabilityEx reachabilityForInternetConnection] retain];
        [internetReach startNotifier];
        [self updateInterfaceWithReachability: internetReach];
        
        wifiReach = [[ReachabilityEx reachabilityForLocalWiFi] retain];
        [wifiReach startNotifier];
        [self updateInterfaceWithReachability: wifiReach];
    }*/
    //NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //[formatter setDateFormat:@"MM-dd-hh-mm-ss"];
    //NSString*locationString=[formatter stringFromDate: [NSDate date]];
    //NSLog(@"<=========检查网络状态(%@)========>", locationString);
    //[formatter release];
    
    if (1/*!m_bIsCheckNet*/)
    {
        m_bIsCheckNet = YES;
        m_NetTimer    = nil;
        
        struct sockaddr_in zeroAddress;
        bzero(&zeroAddress, sizeof(zeroAddress));
        zeroAddress.sin_len = sizeof(zeroAddress);
        zeroAddress.sin_family = AF_INET;
        
        // Recover reachability flags
        SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
        SCNetworkReachabilityFlags flags;
        
        BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
        CFRelease(defaultRouteReachability);
        
        if (!didRetrieveFlags)
        {
            return NO;
        }
        
        BOOL isReachable = flags & kSCNetworkFlagsReachable;
        BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
        (isReachable && !needsConnection) ? (m_bIsNetWork = YES) : (m_bIsNetWork = NO);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:MSG_NETWORK_STATE object:[NSNumber numberWithBool:m_bIsNetWork]];
        
        //启动检测网络定时器
        if (m_bIsCheckNet)
        {
            [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(CheckNetwork) userInfo:nil repeats:NO];
        }
    }
    
    return m_bIsNetWork;
}

-(BOOL)IsContainChinese:(NSString *)source
{
    NSString *emailRegex   = @"[\u4e00-\u9fa5]"; 
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; 
    return [emailTest evaluateWithObject:source];
}

-(void)CreateAppDirectory
{
    NSString *ret = nil;
    
    //所有浏览过的美食图片存放文件夹
    if (nil != (ret = [self CreatePathInApp:@"Documents" SubPath:@"DeliciousImages"]))
    {
        [m_DelImagesPath release];
        m_DelImagesPath = [[NSString alloc] initWithString:ret];
    }
    
    //创建非本地用户信息图片
    if (nil != (ret = [self CreatePathInApp:@"Documents" SubPath:@"FriendsImages"]))
    {
        [m_FriendsimagesPath release];
        m_FriendsimagesPath = [[NSString alloc] initWithString:ret];
    }
    
    //create directory of draft
    if (nil != (ret = [self CreatePathInApp:@"Documents" SubPath:@"Draft"]))
    {
        [m_DraftPath release];
        m_DraftPath = [[NSString alloc] initWithString:ret];
    }
    
    //头像
    if (nil != (ret = [self CreatePathInApp:@"Documents" SubPath:@"icons"]))
    {
        [m_IConsPath release];
        m_IConsPath = [[NSString alloc] initWithString:ret];
    }
    
    //temp
    if (nil != (ret = [self CreatePathInApp:@"Documents" SubPath:@"temp"]))
    {
        ;//
    }
}

-(void)SaveImage:(UIImage*)image Path:(NSString*)path Compress:(float)compress
{
    NSData *data = UIImageJPEGRepresentation(image, compress);
    [data writeToFile:path atomically:NO];
}

-(NSString*)SvaeImageToDir:(UIImage*)image Path:(NSString*)path FileName:(NSString*)filename
{
    NSMutableString *imagepath = [NSMutableString string];
    [imagepath appendFormat:@"%@/%@", path, filename];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:imagepath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:imagepath error:nil];
    }
    
    NSData *data = UIImageJPEGRepresentation(image, 0.9);
    if ([data writeToFile:imagepath atomically:NO])
    {
        return imagepath;
    }
    
    return nil;
}

-(void)RemovePathInApp:(NSString*)mainpath SubPath:(NSString*)subpath
{
    NSString *rootpath = NSHomeDirectory();
    
    NSMutableString *path = [NSMutableString stringWithCapacity:5];
    [path appendString:rootpath];
    [path appendString:@"/"];
    [path appendString:mainpath];
    [path appendString:@"/"];
    [path appendString:subpath];
    
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

-(NSString*)CreatePathInApp:(NSString*)mainpath SubPath:(NSString*)subpath
{
    NSString *rootpath = NSHomeDirectory();
    
    NSMutableString *path = [NSMutableString stringWithCapacity:5];
    [path appendString:rootpath];
    [path appendString:@"/"];
    [path appendString:mainpath];
    [path appendString:@"/"];
    [path appendString:subpath];
    
    if ([[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil])
    {
        return path;
    }
    
    return nil;
}

-(NSString*)GetFilePathInApp:(NSString*)mainpath SubPath:(NSString*)subpath FileName:(NSString*)fielname
{
    NSString *rootpath = NSHomeDirectory();
    
    NSMutableString *path = [NSMutableString stringWithCapacity:7];
    [path appendString:rootpath];
    [path appendString:@"/"];
    [path appendString:mainpath];
    [path appendString:@"/"];
    [path appendString:subpath];
    [path appendString:@"/"];
    [path appendString:fielname];
    
    return path;
}

-(NSString*)PathIsInApp:(NSString*)mainpath SubPath:(NSString*)subpath
{
    NSString *rootpath = NSHomeDirectory();
    
    NSMutableString *path = [NSMutableString stringWithCapacity:5];
    [path appendString:rootpath];
    [path appendString:@"/"];
    [path appendString:mainpath];
    
    NSString *str = nil;
    NSArray *subpathes = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    for (int i=0; i<[subpathes count]; i++)
    {
        str = [subpathes objectAtIndex:i];
        if ([str isEqualToString:subpath])
        {
            [path appendString:@"/"];
            [path appendString:subpath];
            return path;
        }
    }
    
    return nil;
}

-(NSString*)FileIsInExitPath:(NSString*)mainpath SubPath:(NSString*)subpath FileName:(NSString*)fielname
{
    NSString *str = [self PathIsInApp:mainpath SubPath:subpath];
    if (str)
    {
        str = [NSString stringWithFormat:@"%@/%@", str, fielname];
        if ([[NSFileManager defaultManager] fileExistsAtPath:str])
        {
            return str;
        }
    }
    
    return nil;
}

-(NSString*)WriteFileToExistPath:(NSString*)mainpath SubPath:(NSString*)subpath Data:(NSData*)data FileName:(NSString*)fielname
{
    NSString *str = [self FileIsInExitPath:mainpath SubPath:subpath FileName:fielname];
    if (str)
    {
        if (![[NSFileManager defaultManager] removeItemAtPath:str error:nil])
        {
            return nil;
        }
    }
    //创建文件
    str = [NSString stringWithFormat:@"%@/%@/%@/%@", NSHomeDirectory(), mainpath, subpath, fielname];

    if ([[NSFileManager defaultManager] createFileAtPath:str contents:data attributes:nil])
    {
        //创建成功
        return str;
    }

    return nil;
}

-(NSData*)GetFileFromExistPath:(NSString*)mainpath SubPath:(NSString*)subpath FileName:(NSString*)fielname
{
    NSString *str = [self FileIsInExitPath:mainpath SubPath:subpath FileName:fielname];
    if (str)
    {

        NSData *data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", str, fielname]];
            
        return data;
    }
    
    return nil;
}

-(NSString*)RemoveFileInApp:(NSString*)mainpath SubPath:(NSString*)subpath FileName:(NSString*)fielname
{
    NSString *str = [self PathIsInApp:mainpath SubPath:subpath];
    if (str)
    {
        if ([[NSFileManager defaultManager] removeItemAtPath:str error:nil])
        {
            return str;
        }
    }
    
    return nil;
}

-(void)RemoveFile:(NSString*)path
{
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

//时间相关
-(NSString*)GetTimeFormatString
{
    NSDate *date = [[NSDate alloc] init];
	NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
	[dateformat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSString *time = [NSString stringWithString:[dateformat stringFromDate:date]];
	
	[date release];
	[dateformat release];
	
	return time;
}

-(long long)DateToInt:(NSString*)date
{
    NSDateFormatter *format = [[[NSDateFormatter alloc] init] autorelease];
    [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
    NSDate *DATE = [format dateFromString:date];
    return (long long)[DATE timeIntervalSince1970]; 
}

-(NSDate*)IntToDate:(long long)time
{
    return [NSDate dateWithTimeIntervalSince1970:time];
}

-(void)GetOSCurLanguage
{
    NSString *language = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0];

    if ([language isEqualToString:@"zh-Hans"])
    {
        self.m_Language = zhHans;
    }
    else 
    {
        self.m_Language = en;
    }
}

@end


@implementation UITextField (Check)

-(void)IsNameRightFormat:(int)length
{
    if ([self.text length] > 0)
    {
        NSRange range     = {[self.text length]-1, 1};
        NSString *value   = [self.text substringWithRange:range];
        unichar character = [self.text characterAtIndex:[self.text length]-1];
        NSString *set     = nil;
        
        //中文
        if ([[AppConfig DefaultAppConfig] IsContainChinese:value])
        {
            range.length   = [self.text length]-1;
            range.location = 0;
            set = [NSString stringWithString:[self.text substringWithRange:range]];
            self.text = set;
        }
        //length
        else if ([self.text length] > length)
        {
            range.length   = length;
            range.location = 0;
            set = [NSString stringWithString:[self.text substringWithRange:range]];
            self.text = set;
        }
        else if ([value isEqualToString:@"@"])
        {
            return;
        }
        //数字，字母，'.','_'
        else if ((character < 48) || ((character > 57) && (character < 65)) || ((character > 90) && (character < 97)) || (character > 122))
        {
            //'.','_'
            if (('.' == character) || ('_' == character))
            {
                return;
            }
            else 
            {
                range.length   = [self.text length]-1;
                range.location = 0;
                set = [NSString stringWithString:[self.text substringWithRange:range]];
                self.text = set;
            }
        }
        else {;}
    }
}

-(void)IsPwdRightFormat:(int)length
{
    if ([self.text length] > 0)
    {
        NSRange range     = {[self.text length]-1, 1};
        NSString *value   = [self.text substringWithRange:range];
        unichar character = [self.text characterAtIndex:[self.text length]-1];
        NSString *set     = nil;
        
        //中文
        if ([[AppConfig DefaultAppConfig] IsContainChinese:value])
        {
            range.length   = [self.text length]-1;
            range.location = 0;
            set = [NSString stringWithString:[self.text substringWithRange:range]];
            self.text = set;
        }
        //length
        else if ([self.text length] > length)
        {
            range.length   = length;
            range.location = 0;
            set = [NSString stringWithString:[self.text substringWithRange:range]];
            self.text = set;
        }
        //数字，字母，'.','_'
        else if ((character < 48) || ((character > 57) && (character < 65)) || ((character > 90) && (character < 97)) || (character > 122))
        {
            //'.','_'
            if (('.' == character) || ('_' == character))
            {
                return;
            }
            else 
            {
                range.length   = [self.text length]-1;
                range.location = 0;
                set = [NSString stringWithString:[self.text substringWithRange:range]];
                self.text = set;
            }
        }
        else 
        {
            ;
        } 
    }
}

-(void)IsChineseRightFormat
{
    if ([self.text length] > 0)
    {
        NSRange  range  = {[self.text length]-1, 1};
        NSString *value = [self.text substringWithRange:range];
        NSString *set   = nil;
        
        //中文
        if ([[AppConfig DefaultAppConfig] IsContainChinese:value])
        {
            range.length   = [self.text length]-1;
            range.location = 0;
            set = [self.text substringWithRange:range];
            self.text = set;
        }
    }
}

-(void)IsNickRightFormat:(int)length
{
    if ([self.text length] > 0)
    {
        NSRange range   = {[self.text length]-1, 1};
        NSString *value = [self.text substringWithRange:range];
        NSString *set   = nil;
        
        //length
        if ([self.text length] > length)
        {
            range.length   = length;
            range.location = 0;
            set = [self.text substringWithRange:range];
            self.text = set;
        }
        //不能是空格
        else if ([value isEqualToString:@" "])
        {
            range.length   = [self.text length]-1;
            range.location = 0;
            set = [self.text substringWithRange:range];
            self.text = set;
        }
        else {;}
    }
}

@end
